import shutil as sh
from pathlib import Path


def _which(cmd: str, path: Path | None) -> Path | None:
    _path = str(path.resolve()) if path else None
    result = sh.which(cmd=cmd, path=_path)
    if result:
        return Path(result)
    return None


class PandaTools:
    def __init__(self, *, build_dir: Path | None):
        self.build_dir = build_dir

    def es2panda(self) -> Path | None:
        return _which('es2panda', self.build_dir)


BIN_DIR = 'bin'


def find_in_parents_build_bin_dir(
    from_dir: Path = Path(),
    *,
    build_dir: Path = Path('build'),
) -> Path | None:
    resolved = from_dir.resolve()
    for dir in [resolved, *resolved.parents]:
        if (dir / build_dir / BIN_DIR).exists():
            return dir / build_dir
    return None
